﻿import mx.utils.Delegate;

import com.fangmeiti.control.event.EventSlider;
import com.mixmedia.mx.AbstractMovieClipEventDispatcher;
import com.mixmedia.mx.IEventDispatcher;

/**
 * @author Colin
 */
class com.fangmeiti.control.Slider extends AbstractMovieClipEventDispatcher implements IEventDispatcher{
	private var max:Number=100;
	private var seekMax:Number=0;
	private var _value:Number;
	
	private var mcThumb:MovieClip;
	private var mcSliderMax:MovieClip;
	private var mcBG:MovieClip;
	
	private var xs:Number;
	private var ys:Number;

	private var isDrag : Boolean;

	private var iid : Number;

	private var lastThumbPosWhileDrag : Number;
	private var lastThumbPosUpdate:Boolean = false;

	public function Slider(){
		xs = _xscale;
		ys = _yscale;
		_xscale = 100;
		_yscale = 100;

		_width = xs;
		mcSliderMax._xscale=0;
		
		mcThumb.onPress = Delegate.create(this,thumbPress);
		mcThumb.onRelease = Delegate.create(this,thumbRelease);
		mcThumb.onReleaseOutside = Delegate.create(this,thumbRelease);
		
		mcSliderMax.onPress = Delegate.create(this,thumbPress);
		mcSliderMax.onReleaseOutside = Delegate.create(this,thumbRelease);
	}

	public function setMax(value:Number){
		max = value;
	}

	public function getMax():Number{
		return max;
	}
	
	public function setSeekMax(value:Number){
		seekMax =value;
		mcSliderMax._xscale = seekMax/max*xs;
	}
	
	private function thumbPress(){
		isDrag = true;

		dispatchEvent(new EventSlider(this,EventSlider.EVENTDRAG,value));

		clearInterval(iid);
		iid= setInterval(Delegate.create(this,userChangeValue),500);
	}

	private function thumbRelease(){
		clearInterval(iid);
		isDrag = false;
		limitThumbPos();
		userChangeValue();

		dispatchEvent(new EventSlider(this,EventSlider.EVENTDROP,value));
	}

	private function limitThumbPos(){
		var currMaxPos:Number =seekMax/max*xs; 
		if(mcThumb._x>currMaxPos)mcThumb._x = currMaxPos;
		if(mcThumb._x<0)mcThumb._x = 0;	
	}

	private function onEnterFrame(){
		if(isDrag==true){
			mcThumb._x = _xmouse;
			limitThumbPos();

			if(mcThumb._x==lastThumbPosWhileDrag&&lastThumbPosUpdate!=true){
				userChangeValue();
				lastThumbPosUpdate = true;
				return;
			}
			if(mcThumb._x!=lastThumbPosWhileDrag){
				lastThumbPosWhileDrag = mcThumb._x;
				lastThumbPosUpdate = false;
			}
		}
	} 

	private function userChangeValue(){
		var oldValue:Number = _value;
		_value = (mcThumb._x/xs)*max;

		if(oldValue!=_value)dispatchEvent(new EventSlider(this,EventSlider.EVENTCHANGE,value));
	}

	public function set value(value:Number){
		if(isDrag==true)return;
		if(value>max)value = max;
		_value = value;
		mcThumb._x = value/max*xs;
	}
	
	public function get value():Number{
		return _value;
	}
	
	public function set _width(num:Number){
		xs = num;
		mcBG._xscale = xs;
		setSeekMax(seekMax);
	}
	
	public function get _width():Number{
		return Number(xs);
	}
}